﻿using Newtonsoft.Json;
using System;
using System.Globalization;

namespace DbJobsApi.Extensions
{
    /// <summary>
    /// DateTime的Json格式化转换器
    /// </summary>
    public class DateConverter : JsonConverter
    {
        private readonly string _format;
        /// <summary>
        /// DateTime的Json格式化转换器
        /// </summary>
        /// <param name="format">例如yyyyMMdd HH:mm:ss</param>
        public DateConverter(string format)
        {
            _format = format;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsSubclassOf(typeof(double));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value != null)
            {
                if (DateTime.TryParse(reader.Value.ToString(), out DateTime result))
                    return result;
                else
                    return null;
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var val = (DateTime?)value;
            if (val.HasValue)
            {
                writer.WriteValue(val.Value.ToString(_format));
            }
            else
            {
                writer.WriteValue("");
            }
        }
    }
}
